package cn.seapon.talker;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.seapon.talker.common.UserInformation;
import cn.seapon.talker.net.HttpRequest;

public class SearchFriendActivity extends Activity implements OnClickListener,OnItemClickListener{
	
	private SearchListAdapter adapter;
	private static final String TAG = "||__SearchActivity__||";
	private static final String SearchUrl = "http://1.lichtung.sinaapp.com/appserver/appservice.php?request_code=3001";
	private ArrayList<UserInformation> searchResult = new ArrayList<UserInformation>();
	
	private EditText et_input;
	private Button search_btn;
	private ListView lv_searchList;
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -1:
				Toast.makeText(SearchFriendActivity.this, "网络故障！", Toast.LENGTH_SHORT).show();
				break;
			case 1:
				refreshList();
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_friend);
		
		et_input = (EditText) findViewById(R.id.et_input);
		search_btn = (Button) findViewById(R.id.search_btn);
		lv_searchList = (ListView) findViewById(R.id.lv_searchList);
		
		search_btn.setOnClickListener(this); 
		
		new SearchListAdapter(searchResult, this);
		lv_searchList.setAdapter(adapter);
		lv_searchList.setOnItemClickListener(this);
	}
	
	

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.search_btn:
			String inputString = et_input.getText().toString().trim();
			Log.d(TAG, "输入的是："+inputString);
			final String urlString;
			try {
				urlString = SearchUrl+"&search_id="+URLEncoder.encode(inputString,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return ;
			}
			new Thread(){

				@Override
				public void run() {
					searchResult = getSearchResult(urlString);
					Message message = Message.obtain();
					if (searchResult == null) {
						message.what = -1;
					}else {
						message.what = 1;
					}
					handler.sendMessage(message);
				}
				
			}.start();
			break;

		default:
			break;
		}
	}

	public class SearchListAdapter extends BaseAdapter{
		private Context context;
		private ArrayList<UserInformation> informations ;
		
		public void resetData(ArrayList<UserInformation> searchResult){
			this.informations = searchResult;
		}

		public SearchListAdapter(ArrayList<UserInformation> searchResult,
				Context context) {
			this.informations = searchResult;
			this.context = context;
		}

		@Override
		public int getCount() {
			return informations.size();
		}

		@Override
		public Object getItem(int position) {
			return informations.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.search_list_item, parent, false);
			}
			UserInformation information = informations.get(position);
			ImageView iv_avatar = (ImageView) convertView.findViewById(R.id.iv_icon);
			TextView tv_name = (TextView) convertView.findViewById(R.id.tv_title);
			TextView tv_signature = (TextView) convertView.findViewById(R.id.tv_msg);
			iv_avatar.setImageResource(R.drawable.avatar_100);
			String userid	 = information.getAccount();
			String nickname = information.getNickname();
			if (!TextUtils.isEmpty(nickname)) {
				tv_name.setText(userid+"("+nickname+")");
			}else {
				tv_name.setText(userid);
			}
			tv_signature.setText(information.getSignature());
			convertView.setTag(information);
			return convertView;
		}
		
	}
	
	private ArrayList<UserInformation> getSearchResult(String urlString){
		ArrayList<UserInformation> userInformations = new ArrayList<UserInformation>();
		try {
			String retString = HttpRequest.doGetRequest(urlString);
			
			//引入org.json包
			JSONArray jsonArray = new JSONArray(retString);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject object = (JSONObject) jsonArray.get(i);
				UserInformation userInformation = new UserInformation(object.getString("userid"),
						object.getString("tinyname"), object.getString("signature"), 
						object.getString("phone"), object.getString("email"));
				userInformations.add(userInformation);
			}
		}catch (JSONException e) {
			e.printStackTrace();
			return null;
		} 
		return userInformations;
	}

	private void refreshList(){
		if(null==adapter){
			adapter = new SearchListAdapter(searchResult, this);
			lv_searchList.setAdapter(adapter);
		}else{
			adapter.resetData(searchResult);
			adapter.notifyDataSetChanged(); 
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		UserInformation information = (UserInformation) view.getTag();
		String accountString = information.getAccount();
		if ((accountString ==null) || (TextUtils.isEmpty(accountString))) {
			Log.e(TAG, "绑定的数据出错！");
			return;
		}
		Intent intent = new Intent();
		intent.putExtra("userinfo", information);
		intent.setClass(SearchFriendActivity.this, FriendDetailActivity.class);
		startActivity(intent);
	}

}
